import com.sun.xml.internal.ws.api.ResourceLoader;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class ATMSystem {
    static final int MAXUSER = 10;
    static List<Account> g_users = new ArrayList<>(MAXUSER);
    static Account g_loginuser = null; // 记录当前的登录用户
    static int g_pos = -1; // 当前用户在数组中的位置

    public static void main(String[] args) throws IOException {
        init();
        if (loginView()) {
            mainMenu();
            saveInfo();
        } else {
            System.out.println("无效用户");
        }
    }


    private static void init() throws IOException {
//        File file = new File("account_in.txt");
//        BufferedReader reader = new BufferedReader(new FileReader(file));
        String fileName = "/account_in.txt";

        try (InputStream inputStream = ResourceLoader.class.getResourceAsStream(fileName)) {
            if (inputStream == null) {
                System.out.println("文件未找到: " + fileName);
                return;
            }

            // 将输入流转换为 BufferedReader 进行读取
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] parts = line.split(";");
                    int id = Integer.parseInt(parts[0]);
                    String username = parts[1];
                    String password = parts[2];
                    float money = Float.parseFloat(parts[3]);
                    g_users.add(new Account(id, username, password, money));
                }
                reader.close();
            }

        } catch (IOException e) {
            System.err.println("读取文件时发生错误: " + e.getMessage());
        }


    }

    private static boolean loginView() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入账户编号\n");
        int uid = scanner.nextInt();
        System.out.print("输入用户密码\n");
        String password = scanner.next();
        return userLogin(uid, password);
    }

    private static boolean userLogin(int userId, String passwd) {
        for (int i = 0; i < g_users.size(); i++) {
            Account account = g_users.get(i);
            if (userId == account.id && passwd.equals(account.password)) {
                g_loginuser = account;
                g_pos = i;
                return true;
            }
        }
        return false;
    }

    private static void mainMenu() {
        Scanner scanner = new Scanner(System.in);
        boolean running = true;
        while (running) {
            System.out.println("欢迎使用ATM机");
            System.out.println("=============");
            System.out.println("1. 取款           2. 查询");
            System.out.println("3. 修改密码       4. 转账");
            System.out.println("5. 退出系统");
            System.out.println("=============");
            System.out.println("请选择服务:");
            switch (scanner.nextLine()) {
                case "1": withdraw(); break;
                case "2": selectUser(); break;
                case "3": updatePassword(); break;
                case "4": transfer(); break;
                case "5": running = false;break;
                default: System.out.println("输入无效，请重新输入");
            }
        }
    }

    private static void withdraw() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入取款金额\n");
        int m = scanner.nextInt();
        if (m > 0 && m <= g_loginuser.money) {
            g_loginuser.money -= m;
            System.out.printf("请取出现金 %d\n余额为 %.2f\n", m, g_loginuser.money);
        }
        mainMenu();
    }

    private static void selectUser() {
        displayUser(g_loginuser);
        mainMenu();
    }

    private static void updatePassword() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入原密码\n");
        String oldPass = scanner.next();
        if (oldPass.equals(g_loginuser.password)) {
            System.out.print("输入新密码\n");
            String newPassword = scanner.next();
            System.out.print("再输入一次新密码\n");
            String newPassword2 = scanner.next();
            if (newPassword.equals(newPassword2)) {
                g_loginuser.password = newPassword;
                System.out.println("修改密码成功!");
            }
        }
        mainMenu();
    }

    private static void transfer() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入对方帐号\n");
        int uid = scanner.nextInt();
        int pos = isvalidAccount(uid);
        if (pos != -1) {
            System.out.print("输入转账金额\n");
            int m = scanner.nextInt();
            if (m <= g_loginuser.money) {
                g_loginuser.money -= m;
                g_users.get(pos).money += m;
                System.out.printf("转出 %d 到 %s \n余额 %.2f \n", m, g_users.get(pos).username, g_loginuser.money);
            }
        }
        mainMenu();
    }

    private static int isvalidAccount(int uid) {
        for (int i = 0; i < g_users.size(); i++) {
            if (uid == g_users.get(i).id && uid != g_loginuser.id) {
                return i;
            }
        }
        return -1;
    }

    private static void displayUser(Account user) {
        System.out.println("当前用户信息");
        System.out.println("============");
        System.out.printf("用户帐号: %d\n用户姓名: %s\n用户密码: %s\n账户余额: %.2f\n",
                user.id, user.username, user.password, user.money);
    }

    private static void saveInfo() throws IOException {
        Path path = Paths.get("account_out.txt");
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
            for (Account account : g_users) {
                String content = String.format("%d;%s;%s;%.2f\n", account.id, account.username, account.password, account.money);
                writer.write(content);
            }
        }
    }
}